import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../animations/animation_config.dart';

/// 按钮状态枚举
enum ButtonState {
  idle,
  loading,
  success,
  error,
  disabled,
}

/// 按钮类型枚举
enum StateButtonType {
  elevated,
  filled,
  outlined,
  text,
  icon,
}

/// 状态按钮组件
/// 提供可预期的交互反馈和状态变化动画
class StateButton extends StatefulWidget {
  const StateButton({
    super.key,
    required this.onPressed,
    required this.child,
    this.state = ButtonState.idle,
    this.type = StateButtonType.elevated,
    this.width,
    this.height = 48,
    this.padding,
    this.margin,
    this.borderRadius,
    this.backgroundColor,
    this.foregroundColor,
    this.disabledBackgroundColor,
    this.disabledForegroundColor,
    this.loadingWidget,
    this.successWidget,
    this.errorWidget,
    this.successDuration = const Duration(seconds: 2),
    this.errorDuration = const Duration(seconds: 2),
    this.enableFeedback = true,
    this.enableHapticFeedback = true,
  });

  /// 点击回调
  final VoidCallback? onPressed;
  
  /// 子组件
  final Widget child;
  
  /// 按钮状态
  final ButtonState state;
  
  /// 按钮类型
  final StateButtonType type;
  
  /// 宽度
  final double? width;
  
  /// 高度
  final double height;
  
  /// 内边距
  final EdgeInsetsGeometry? padding;
  
  /// 外边距
  final EdgeInsetsGeometry? margin;
  
  /// 圆角
  final BorderRadius? borderRadius;
  
  /// 背景色
  final Color? backgroundColor;
  
  /// 前景色
  final Color? foregroundColor;
  
  /// 禁用状态背景色
  final Color? disabledBackgroundColor;
  
  /// 禁用状态前景色
  final Color? disabledForegroundColor;
  
  /// 自定义加载组件
  final Widget? loadingWidget;
  
  /// 自定义成功组件
  final Widget? successWidget;
  
  /// 自定义错误组件
  final Widget? errorWidget;
  
  /// 成功状态持续时间
  final Duration successDuration;
  
  /// 错误状态持续时间
  final Duration errorDuration;
  
  /// 是否启用反馈
  final bool enableFeedback;
  
  /// 是否启用触觉反馈
  final bool enableHapticFeedback;

  @override
  State<StateButton> createState() => _StateButtonState();
}

class _StateButtonState extends State<StateButton>
    with TickerProviderStateMixin {
  late AnimationController _scaleController;
  late AnimationController _fadeController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _scaleController = AnimationConfig.createController(
      vsync: this,
      duration: AnimationConfig.buttonPress,
    );
    _fadeController = AnimationConfig.createController(
      vsync: this,
      duration: AnimationConfig.stateTransition,
    );
    
    _scaleAnimation = AnimationConfig.createScaleAnimation(
      _scaleController,
      begin: 1.0,
      end: 0.95,
    );
    _fadeAnimation = AnimationConfig.createFadeAnimation(_fadeController);
    
    _fadeController.value = 1.0;
  }

  @override
  void didUpdateWidget(StateButton oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.state != oldWidget.state) {
      _handleStateChange();
    }
  }

  void _handleStateChange() {
    _fadeController.reset();
    _fadeController.forward();

    // 自动重置状态
    if (widget.state == ButtonState.success) {
      Future.delayed(widget.successDuration, () {
        if (mounted && widget.state == ButtonState.success) {
          // 这里应该由父组件来处理状态重置
        }
      });
    } else if (widget.state == ButtonState.error) {
      Future.delayed(widget.errorDuration, () {
        if (mounted && widget.state == ButtonState.error) {
          // 这里应该由父组件来处理状态重置
        }
      });
    }
  }

  void _handleTapDown(TapDownDetails details) {
    if (_canInteract()) {
      _scaleController.forward();
    }
  }

  void _handleTapUp(TapUpDetails details) {
    if (_canInteract()) {
      _scaleController.reverse();
    }
  }

  void _handleTapCancel() {
    if (_canInteract()) {
      _scaleController.reverse();
    }
  }

  void _handleTap() {
    if (_canInteract() && widget.onPressed != null) {
      if (widget.enableHapticFeedback) {
        HapticFeedback.lightImpact();
      }
      widget.onPressed!();
    }
  }

  bool _canInteract() {
    return widget.state == ButtonState.idle && widget.onPressed != null;
  }

  bool _isDisabled() {
    return widget.state == ButtonState.disabled || 
           widget.state == ButtonState.loading || 
           widget.onPressed == null;
  }

  @override
  void dispose() {
    _scaleController.dispose();
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      margin: widget.margin,
      child: AnimatedBuilder(
        animation: Listenable.merge([_scaleAnimation, _fadeAnimation]),
        builder: (context, child) {
          return Transform.scale(
            scale: _scaleAnimation.value,
            child: FadeTransition(
              opacity: _fadeAnimation,
              child: _buildButton(),
            ),
          );
        },
      ),
    );
  }

  Widget _buildButton() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    switch (widget.type) {
      case StateButtonType.elevated:
        return ElevatedButton(
          onPressed: _isDisabled() ? null : _handleTap,
          style: _buildButtonStyle(colorScheme),
          child: _buildButtonContent(),
        );
      
      case StateButtonType.filled:
        return FilledButton(
          onPressed: _isDisabled() ? null : _handleTap,
          style: _buildButtonStyle(colorScheme),
          child: _buildButtonContent(),
        );
      
      case StateButtonType.outlined:
        return OutlinedButton(
          onPressed: _isDisabled() ? null : _handleTap,
          style: _buildButtonStyle(colorScheme),
          child: _buildButtonContent(),
        );
      
      case StateButtonType.text:
        return TextButton(
          onPressed: _isDisabled() ? null : _handleTap,
          style: _buildButtonStyle(colorScheme),
          child: _buildButtonContent(),
        );
      
      case StateButtonType.icon:
        return GestureDetector(
          onTapDown: _canInteract() ? _handleTapDown : null,
          onTapUp: _canInteract() ? _handleTapUp : null,
          onTapCancel: _canInteract() ? _handleTapCancel : null,
          onTap: _canInteract() ? _handleTap : null,
          child: Opacity(
            opacity: _isDisabled() ? 0.5 : 1.0,
            child: Container(
              padding: widget.padding ?? const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _getBackgroundColor(),
                borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
                border: widget.type == StateButtonType.outlined
                    ? Border.all(color: _getBorderColor())
                    : null,
              ),
              child: _buildButtonContent(),
            ),
          ),
        );
    }
  }

  ButtonStyle _buildButtonStyle(ColorScheme colorScheme) {
    return ButtonStyle(
      backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
        if (states.contains(WidgetState.disabled)) {
          return widget.disabledBackgroundColor;
        }
        return _getBackgroundColor();
      }),
      foregroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
        if (states.contains(WidgetState.disabled)) {
          return widget.disabledForegroundColor;
        }
        return _getForegroundColor();
      }),
      padding: WidgetStateProperty.all(
        widget.padding ?? const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
      ),
      shape: WidgetStateProperty.all(
        RoundedRectangleBorder(
          borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
        ),
      ),
      elevation: WidgetStateProperty.all(
        widget.type == StateButtonType.elevated ? 2 : 0,
      ),
    );
  }

  Color? _getBackgroundColor() {
    if (widget.backgroundColor != null) {
      return widget.backgroundColor;
    }

    final colorScheme = Theme.of(context).colorScheme;
    
    switch (widget.state) {
      case ButtonState.success:
        return colorScheme.primary;
      case ButtonState.error:
        return colorScheme.error;
      case ButtonState.disabled:
        return colorScheme.onSurface.withOpacity(0.12);
      case ButtonState.loading:
      case ButtonState.idle:
        return widget.type == StateButtonType.outlined || widget.type == StateButtonType.text
            ? null
            : colorScheme.primary;
    }
  }

  Color? _getForegroundColor() {
    if (widget.foregroundColor != null) {
      return widget.foregroundColor;
    }

    final colorScheme = Theme.of(context).colorScheme;
    
    switch (widget.state) {
      case ButtonState.success:
        return colorScheme.onPrimary;
      case ButtonState.error:
        return colorScheme.onError;
      case ButtonState.disabled:
        return colorScheme.onSurface.withOpacity(0.38);
      case ButtonState.loading:
      case ButtonState.idle:
        return widget.type == StateButtonType.outlined || widget.type == StateButtonType.text
            ? colorScheme.primary
            : colorScheme.onPrimary;
    }
  }

  Color _getBorderColor() {
    final colorScheme = Theme.of(context).colorScheme;
    
    switch (widget.state) {
      case ButtonState.success:
        return colorScheme.primary;
      case ButtonState.error:
        return colorScheme.error;
      case ButtonState.disabled:
        return colorScheme.onSurface.withOpacity(0.12);
      case ButtonState.loading:
      case ButtonState.idle:
        return colorScheme.outline;
    }
  }

  Widget _buildButtonContent() {
    switch (widget.state) {
      case ButtonState.loading:
        return widget.loadingWidget ?? 
               Row(
                 mainAxisSize: MainAxisSize.min,
                 children: [
                   SizedBox(
                     width: 16,
                     height: 16,
                     child: CircularProgressIndicator(
                       strokeWidth: 2,
                       valueColor: AlwaysStoppedAnimation(
                         _getForegroundColor() ?? Theme.of(context).colorScheme.onPrimary,
                       ),
                     ),
                   ),
                   const SizedBox(width: 8),
                   const Text('加载中...'),
                 ],
               );
      
      case ButtonState.success:
        return widget.successWidget ?? 
               Row(
                 mainAxisSize: MainAxisSize.min,
                 children: [
                   Icon(
                     Icons.check,
                     size: 20,
                     color: _getForegroundColor(),
                   ),
                   const SizedBox(width: 8),
                   const Text('成功'),
                 ],
               );
      
      case ButtonState.error:
        return widget.errorWidget ?? 
               Row(
                 mainAxisSize: MainAxisSize.min,
                 children: [
                   Icon(
                     Icons.error_outline,
                     size: 20,
                     color: _getForegroundColor(),
                   ),
                   const SizedBox(width: 8),
                   const Text('失败'),
                 ],
               );
      
      case ButtonState.disabled:
      case ButtonState.idle:
        return widget.child;
    }
  }
}

/// 预定义的状态按钮样式
class StateButtons {
  
  /// 主要操作按钮
  static Widget primary({
    required VoidCallback? onPressed,
    required Widget child,
    ButtonState state = ButtonState.idle,
    double? width,
    double height = 48,
  }) {
    return StateButton(
      onPressed: onPressed,
      state: state,
      type: StateButtonType.filled,
      width: width,
      height: height,
      child: child,
    );
  }
  
  /// 次要操作按钮
  static Widget secondary({
    required VoidCallback? onPressed,
    required Widget child,
    ButtonState state = ButtonState.idle,
    double? width,
    double height = 48,
  }) {
    return StateButton(
      onPressed: onPressed,
      state: state,
      type: StateButtonType.outlined,
      width: width,
      height: height,
      child: child,
    );
  }
  
  /// 文本按钮
  static Widget text({
    required VoidCallback? onPressed,
    required Widget child,
    ButtonState state = ButtonState.idle,
  }) {
    return StateButton(
      onPressed: onPressed,
      state: state,
      type: StateButtonType.text,
      child: child,
    );
  }
  
  /// 图标按钮
  static Widget icon({
    required VoidCallback? onPressed,
    required Widget icon,
    ButtonState state = ButtonState.idle,
    double size = 48,
  }) {
    return StateButton(
      onPressed: onPressed,
      state: state,
      type: StateButtonType.icon,
      width: size,
      height: size,
      child: icon,
    );
  }
  
  /// 浮动操作按钮
  static Widget fab({
    required VoidCallback? onPressed,
    required Widget child,
    ButtonState state = ButtonState.idle,
    bool mini = false,
  }) {
    return StateButton(
      onPressed: onPressed,
      state: state,
      width: mini ? 40 : 56,
      height: mini ? 40 : 56,
      borderRadius: BorderRadius.circular(mini ? 20 : 28),
      child: child,
    );
  }
}